# 导入蓝图模块
from flask import Blueprint,request,jsonify,json
import json
from db import db1
# 实例化
bp_course = Blueprint("course",__name__)
from comm import get_data

#接口
@bp_course.route('/couponM',methods=['POST','GET','PUT','DELETE'])
def couponM():
    # 添加
    if request.method == "POST":
        #获取用户输入
        data = get_data()
        #构造sql语句
        sql = "insert into coupon values(0,'%s',%d,'%s','%s')" % (data['name'],int(data['total']),data['stime'],data['etime'])
        # pymysql
        db1.insert(sql)
        #返回结果
        return jsonify({'code':200})
    
    # 查看
    elif request.method == 'GET':
        # 根据id获取数据
        id = request.args.get('id')
        sql = "select * from coupon where id=%d" % (int(id))
        res =db1.find(sql)
        return jsonify({'code':200,'coupon':res})

    # 修改
    elif request.method == "PUT":
        # 修改
        # 获取用户输入
        id = request.args.get('id')
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造sql语句 update 表名 set 字段名1=值,字段名2=值 where id=1
        sql = "update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"%(data['name'],int(data['total']),data['stime'],data['etime'],int(id))  #小猴同志所输
        db1.insert(sql)
        return jsonify({'code':200})

    # 删除
    elif request.method == "DELETE":
        # 获取id
        id = request.args.get('id')
        sql = "delete from coupon where id=%d"%(int(id))
        db1.insert(sql)
        return jsonify({'code':200})


#部门管理
@bp_course.route('/deptM',methods=['POST','GET'])
def deptM():
    if request.method == "POST":
        data = get_data()
        #判断名字是否已经存在
        sql = "select id from dept where name='%s'"%(data['name'])
        res = db1.find(sql)
        #存在直接返回
        if res:
            return jsonify({"code":10011,'mes':'已经存在'})
        #不存在添加
        else:
            sql = "insert into dept(name) values('%s')"%(data['name'])
            db1.insert(sql)
            return jsonify({"code":200})
    else:
        sql = "select * from dept"
        res = db1.findall(sql)
        return jsonify({"code":200,'list':res})      

# 员工添加接口
@bp_course.route('/empM',methods=['POST','GET'])
def empM():
    if request.method == "POST":
        data = get_data()
        #添加员工
        sql = "insert into emp values(0,'%s',%d,%.2f,%d)"%(data['name'],int(data['sex']),float(data['salary']),int(data['dept_id']))
        db1.insert(sql)
        #更新部门表员工总数
        sql1 = 'select total from dept where id=%d'%(int(data['dept_id']))
        res = db1.find(sql1)
        total = int(res['total'])+1
        sql2 = 'update dept set total=%d where id=%d'%(total,int(data['dept_id']))
        db1.insert(sql2)
        return jsonify({"code":200})


